package com.seqb.common.task;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seqb.common.utils.RedisUtils;
import com.seqb.utils.JsonUtils;
import com.seqb.utils.Md5Utils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author lilinshen
 * @title 新冠疫苗定时任务
 * @description 请填写相关描述
 * @date 2021/06/03
 */
public class XinGuanYiMiaoJob implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(XinGuanYiMiaoJob.class);
    public static HttpHeaders headers = new HttpHeaders();

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        headers = new HttpHeaders();
        try {
            String email = "";
            Object taskParams = redisUtils.get("taskParams");
            if (null != taskParams) {
                JSONArray parseArray = JSON.parseArray(taskParams.toString());
                for (int i = 0; i < parseArray.size(); i++) {
                    JSONObject item = parseArray.getJSONObject(i);
                    String type = item.getString("type");
                    if ("XinGuanYiMiaoJob".equals(type)) {
                        JSONArray value = item.getJSONArray("value");
                        for (int j = 0; j < value.size(); j++) {
                            JSONObject jsonObject = value.getJSONObject(j);

                            String key = jsonObject.getString("key");
                            if ("email".equals(key)) {
                                email = key;
                            } else {
                                headers.add(jsonObject.getString("key"), jsonObject.getString("value"));
                            }
                        }
                    }
                }
            }
            //LOGGER.info("新冠疫苗定时任务开始-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            setSecurityHeader();
            checkInventory(email);
            //LOGGER.info("新冠疫苗定时任务结束-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查库存可预约任务操作
     */
    public boolean checkInventory(String email) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String requestUrl = "https://www.zsyjjkw.com/epi-web/*.jsonRequest";
            HttpMethod httpMethod = HttpMethod.POST;
            Map<String, Object> commonMap = new HashMap<>();
            commonMap.put("tag", "1");
            commonMap.put("companyName", "");
            commonMap.put("streetId", "");
            List paramList = new ArrayList<>();
            paramList.add(commonMap);
            HttpEntity httpEntity = new HttpEntity(JsonUtils.beanToJson(paramList), headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                //新冠疫苗定时任务
                System.out.println("新冠疫苗定时任务：" + entityBody);
                JSONObject entityJson = JSONObject.parseObject(entityBody);
                String code = entityJson.getString("code");
                if ("200".equals(code) && null != entityJson.get("body")) {
                    JSONArray list = ((JSONObject) entityJson.get("body")).getJSONArray("list");
                    if (null != list && list.size() > 0) {
                        StringBuffer companyNames = new StringBuffer();
                        StringBuffer companyCodes = new StringBuffer();
                        for (int i = 0; i < list.size(); i++) {
                            JSONObject item = (JSONObject) list.get(i);
                            String markaddress = item.getString("markaddress");
                            String companyName = item.getString("companyName");
                            String companyCode = item.getString("companyCode");
                            //有辖区限制
                            if ("1".equals(markaddress)) {
                                companyName = companyName + "(限辖区)";
                            }
                            companyNames.append(companyName).append("、");
                            companyCodes.append(companyCode).append("、");
                        }
                        if (!companyNames.toString().equals("")) {
                            System.out.println("有可以预约的疫苗接种点");
                            String companyNameStr = companyNames.deleteCharAt(companyNames.length() - 1).toString();
                            String companyCodeStr = companyCodes.deleteCharAt(companyCodes.length() - 1).toString();

                            //每次加1，加到5次后，就不要再发短信了
                            redisUtils.incr(companyCodeStr, 1);
                            int count = (int) redisUtils.get(companyCodeStr);
                            if (count <= 5) {
                                //TODO 发送邮件通知
                                MailUtil.send("lilinshen@cecjx.com", "新冠疫苗定时任务", companyNameStr + "，有号可以预约新冠疫苗。", false);
                                if (!StringUtils.isEmpty(email)) {
                                    String[] emails = email.split(",");
                                    for (int i = 0; i < emails.length; i++) {
                                        String item = emails[i];
                                        MailUtil.send(item, "新冠疫苗定时任务", companyNameStr + "，有号可以预约新冠疫苗。", false);
                                    }
                                }
                                //指定失效时间1小时
                                redisUtils.expire(companyCodeStr, 60 * 60);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("新冠疫苗定时任务执行失败：" + e.getMessage() + e.getCause());
        }
        return false;

    }

    /**
     * 设置认证的请求头
     */
    public void setSecurityHeader() {
        String xSecurityRandmon = RandomUtil.randomNumbers(11);
        long xSecurityTimestamp = (new Date()).getTime();
        String source = "JMHTd1942a3ab01eb59220e2b3a46e7ef09d" + xSecurityTimestamp + xSecurityRandmon;
        String xSecuritySign = Md5Utils.hexMd5(source);
        headers.add("X-Security-sign", xSecuritySign);
        headers.add("X-Security-randmon", xSecurityRandmon);
        headers.add("X-Security-timestamp", String.valueOf(xSecurityTimestamp));
    }


    public static void main(String[] args) {
        String xSecurityRandmon = RandomUtil.randomNumbers(11);
        long xSecurityTimestamp = (new Date()).getTime();
        String source = "JMHTd1942a3ab01eb59220e2b3a46e7ef09d" + xSecurityTimestamp + xSecurityRandmon;
        String xSecuritySign = Md5Utils.hexMd5(source);

        System.out.println(xSecuritySign);
        System.out.println(xSecurityRandmon);
        System.out.println(xSecurityTimestamp);

        String result = Md5Utils.hexMd5("JMHTd1942a3ab01eb59220e2b3a46e7ef09d162303719816145578589075");
        System.out.println(result);
        System.out.println(result.equals("9cf7c4131ecb044fdecf83d8be44d1d7"));
    }

}
